package com.xiaoye.qbproject.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoye.qbproject.domain.BlbcTroops;
import com.xiaoye.qbproject.domain.CountryRegion;
import com.xiaoye.qbproject.mapper.CountryRegionMapper;
import com.xiaoye.qbproject.redis.RedisCache;
import com.xiaoye.qbproject.redis.RedisConstant;
import com.xiaoye.qbproject.service.BlbcTroopsService;
import com.xiaoye.qbproject.service.CountryRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @description 针对表【COUNTRY_REGION(国家、地区)】的数据库操作Service实现
 * @createDate 2024-12-27 01:40:47
 */
@Service
public class CountryRegionServiceImpl extends ServiceImpl<CountryRegionMapper, CountryRegion>
        implements CountryRegionService {
    @Autowired
    private BlbcTroopsService blbcTroopsService;
    @Autowired
    private RedisCache redisCache;

    /**
     * @param countryId
     * @description: 获取国家或地区 下的兵力编程编组
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.CountryRegion
     * @ceateDate: 2024-12-30 12:01
     */
    @Override
    public CountryRegion getBlBcTreeByCountryId(String countryId) {
        // 从缓存中获取数据
        String redisKey = RedisConstant.COUNTRY_DOWN_TROOPS_TREE + countryId;
        CountryRegion countryRegion = redisCache.getCacheObject(redisKey);
        if (countryRegion != null) {
            return countryRegion;
        }
        // 从数据库中获取数据
        countryRegion = baseMapper.selectById(countryId);
        if (countryRegion == null) {
            return null;
        }

        List<BlbcTroops> blbcTroops = blbcTroopsService.list(Wrappers
                .<BlbcTroops>lambdaQuery()
                .eq(BlbcTroops::getCountryId, countryId)
                .select(BlbcTroops::getId, BlbcTroops::getTroopsName, BlbcTroops::getParentId)
        );
        countryRegion.setBlbcTroopsList(blbcTroopsService.buildTree(blbcTroops));
        // 缓存数据
        redisCache.setCacheObject(redisKey, countryRegion, 10, TimeUnit.MINUTES);
        return countryRegion;
    }

    @Override
    public void delCache() {
        redisCache.deleteObject(RedisConstant.COUNTRY_DOWN_TROOPS_TREE + "*");
    }
}




